<template>
  <div class="analy-box-wrap page-wrap">
    <div>
      <Select class="w200" size="small" v-model="selectMember">
        <Option value="all">全部</Option>
        <Option
          v-for="(item, index) in members"
          :key="'mem_' + index"
          :value="item.qq"
          >{{ item.nickname }}</Option
        >
      </Select>
      <Button class="mar10l" type="primary" size="small" @click="doAnaly"
        >分析</Button
      >
      --
      <Checkbox v-model="isShowLeavePeople">显示离开人员</Checkbox>
    </div>
    <div class="time-analy-result">
      <span
        class="result-summary"
        v-html="isShowAllCounts ? showAllCountsSummary : showSummary"
        :class="{ 'result-summary-expand': isExpandSummary }"
      ></span>
      <a @click="isExpandSummary = !isExpandSummary" v-if="isShowAllCounts"
        >--{{ isExpandSummary ? "收起" : "展开" }}</a
      >
      <h3 class="mar10t">提交时间分析</h3>
      <table class="table" v-if="isShowAllCounts">
        <tr>
          <th>
            序号<TableSort
              :order="getSortOrder('no')"
              @changeSort="changeSort('no', $event)"
            ></TableSort>
          </th>
          <th>昵称</th>
          <th>
            总天数
            <TableSort
              :order="getSortOrder('allDays')"
              @changeSort="changeSort('allDays', $event)"
            ></TableSort>
          </th>
          <th>
            日毕次数
            <TableSort
              :order="getSortOrder('daytoDays')"
              @changeSort="changeSort('daytoDays', $event)"
            ></TableSort>
          </th>
          <th>
            23:30后次数<TableSort
              :order="getSortOrder('focusDays')"
              @changeSort="changeSort('focusDays', $event)"
            ></TableSort>
          </th>
          <th>
            踩点次数<TableSort
              :order="getSortOrder('deadlineDays')"
              @changeSort="changeSort('deadlineDays', $event)"
            ></TableSort>
          </th>
          <th>
            超时次数<TableSort
              :order="getSortOrder('delayDays')"
              @changeSort="changeSort('delayDays', $event)"
            ></TableSort>
          </th>
          <th>超时时间</th>
        </tr>
        <tr
          v-for="(item, index) in showCountsList"
          :key="'show_count_' + index"
        >
          <td>{{ item.no }}</td>
          <td>{{ item.nickname }}</td>
          <td class="center">{{ item.allDays }}</td>
          <td class="center">{{ item.daytoDays }}</td>
          <td class="center">{{ item.focusDays }}</td>
          <td class="center">{{ item.deadlineDays }}</td>
          <td class="center">{{ item.delayDays }}</td>
          <td>
            {{ item.delayTimes.join("、") }}
          </td>
        </tr>
      </table>
      <table class="table time-analy-table" v-else>
        <tr>
          <th>周数</th>
          <th>规划</th>
          <th>周一</th>
          <th>周二</th>
          <th>周三</th>
          <th>周四</th>
          <th>周五</th>
        </tr>
        <tr v-for="(item, index) in showTimeList" :key="'time_' + index">
          <td>{{ item.w }}</td>
          <td>{{ item.plan }}</td>
          <td
            v-for="(daytime, index2) in item.days"
            :key="'day_' + index + '_' + index2"
            :class="getTimeClass(item.plan, daytime)"
          >
            {{ daytime || "-" }}
          </td>
        </tr>
      </table>
      <div class="mar10t">
        <h3>按时间段分析</h3>
        <div class="time-count-echart" ref="timeCountChart"></div>
        <div class="time-count-tops">
          <table class="table">
            <tr>
              <th>-</th>
              <th>时间段</th>
              <th>数量</th>
            </tr>
            <tr
              v-for="(item, index) in periodCountList"
              :key="'period_count_' + index"
              v-if="index < 10"
            >
              <td>{{ index + 1 }}</td>
              <td>{{ item.minTime + "-" + item.maxTime }}</td>
              <td>{{ item.count }}</td>
            </tr>
          </table>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { readCSV, parseTen, cloneObj } from "js/utils.js";
import analyMixin from "js/analy.js";
import * as echarts from "echarts";
const dayjs = require("dayjs");
var isSameOrAfter = require("dayjs/plugin/isSameOrAfter");
var relativeTime = require("dayjs/plugin/relativeTime");
require("dayjs/locale/zh-cn");
dayjs.locale("zh-cn");
dayjs.extend(isSameOrAfter);
dayjs.extend(relativeTime);

export default {
  mixins: [analyMixin],
  data() {
    return {
      isLoading: false,
      selectMember: "all",
      isShowLeavePeople: false, // 显示离开人员
      timeList: [],
      timeChart: null,
      sortKey: "daytoDays",
      sortOrder: "desc",
      isExpandSummary: false,
    };
  },
  computed: {
    members() {
      let members = this.$store.getters.getMembers();
      if (!this.isShowLeavePeople) {
        members = members.filter((item) => !item.isLeave);
      }
      return members;
    },
    // 显示所有人员汇总
    isShowAllCounts() {
      return this.selectMember === "all";
    },
    showTimeList() {
      return this.getTimeList(this.selectMember);
    },
    // 提交时间统计x轴
    periodCountXdata() {
      let list = [];
      for (let i = 0, n = 24; i < n; i++) {
        list.push(
          {
            min: i,
            max: i + 0.5,
            minTime: parseTen(i) + ":00",
            maxTime: parseTen(i) + ":30",
          },
          {
            min: i + 0.5,
            max: i + 1,
            minTime: parseTen(i) + ":30",
            maxTime: parseTen(i + 1) + ":00",
          }
        );
      }
      return list;
    },
    // 提交时间统计y轴
    periodCountData() {
      let xData = this.periodCountXdata;
      let numsObj = {};
      for (let i = 0, n = xData.length; i < n; i++) {
        numsObj[i] = 0;
      }
      let qqs = [];
      if (this.isShowAllCounts) {
        qqs = this.members.map((item) => item.qq);
      } else {
        qqs = [this.selectMember];
      }
      for (let qq of qqs) {
        let timeList = this.getTimeList(qq);
        for (let i = 0, n = timeList.length; i < n; i++) {
          let days = timeList[i].days || [];
          for (let j = 0, m = days.length; j < m; j++) {
            let time = days[j];
            checkTime(time);
          }
        }
      }
      let list = [];
      for (let i = 0, n = xData.length; i < n; i++) {
        list.push(numsObj[i]);
      }
      return list;
      function checkTime(time) {
        let nowDate = dayjs().format("YYYY-MM-DD");
        let curTime;
        if (!time || time === "-") {
          return;
        }
        if (time.indexOf("-") > 0) {
          curTime = dayjs(time).format("HH:mm:ss");
        } else {
          curTime = dayjs(nowDate + " " + time).format("HH:mm:ss");
        }
        for (let i = 0, n = xData.length; i < n; i++) {
          let item = xData[i];
          if (curTime >= item.minTime && curTime < item.maxTime) {
            numsObj[i] += 1;
            break;
          }
        }
      }
    },
    // 按提交时间排序
    periodCountList() {
      let list = [];
      let xData = this.periodCountXdata;
      let values = this.periodCountData;
      for (let i = 0, n = xData.length; i < n; i++) {
        let item = xData[i];
        list.push({
          minTime: item.minTime,
          maxTime: item.maxTime,
          count: values[i],
        });
      }
      list = list
        .filter((item) => item.count !== 0)
        .sort((a, b) => (a.count < b.count ? 1 : -1));
      return list;
    },
    // 结果汇总
    showSummary() {
      let str = "";
      let item = this.getCountsByQQ(this.selectMember);
      let strs = [];
      strs.push(`汇总：<span>共参与<a>${item.allDays}</a>天</span>`);
      if (item.delayDays === 0) {
        strs.push(`达成<a>全日毕目标</a>`);
      } else {
        strs.push(`日毕次数<a>${item.daytoDays}</a>次`);
      }
      strs.push(`说到做到<a>${item.planDays}</a>次`);
      // if (item.missPlanDays > 0) {
      //   strs.push(`未做到<a>${item.missPlanDays}</a>次`);
      // }
      if (item.focusDays > 0) {
        strs.push(`23:30后提交<a>${item.focusDays}</a>次`);
      }
      if (item.deadlineDays > 0) {
        strs.push(`踩点<a>${item.deadlineDays}</a>次`);
      }
      if (item.delayDays > 0) {
        strs.push(`超时<a>${item.delayDays}</a>次`);
        if (item.delayTimes.length > 1) {
          let s = item.delayTimes.map((a) => "<a>" + a + "</a>").join("、");
          strs.push(`分别超时${s}`);
        } else {
          strs.push(`超时<a>${item.delayTimes[0]}</a>`);
        }
      }
      str += "<span>" + strs.join("，") + "</span>";
      return str;
    },
    // 显示所有汇总
    allCountsList() {
      let list = [];
      for (let i = 0, n = this.members.length; i < n; i++) {
        let member = this.members[i];
        let item = this.getCountsByQQ(member.qq);
        item.no = member.no;
        item.qq = member.qq;
        item.nickname = member.nickname;
        list.push(item);
      }
      return list;
    },
    // 显示汇总列表
    showCountsList() {
      let list = cloneObj(this.allCountsList);
      let sortKey = this.sortKey;
      if (!sortKey) {
        return list;
      }
      if (this.sortOrder === "asc") {
        list.sort((a, b) => (a[sortKey] > b[sortKey] ? 1 : -1));
      } else {
        list.sort((a, b) => (a[sortKey] < b[sortKey] ? 1 : -1));
      }
      return list;
    },
    // 所有的汇总摘要
    showAllCountsSummary() {
      let str = "";
      let strs = [];
      let allDays = 0;
      let list = this.allCountsList;
      for (let i = 0, n = list.length; i < n; i++) {
        let item = list[i];
        if (item.allDays > allDays) {
          allDays = item.allDays;
        }
      }
      let daytodayMembers = list.filter(
        (item) => allDays > 0 && item.daytoDays === item.allDays
      );
      let planDaysMembers = list.filter(
        (item) => allDays > 0 && item.planDays === item.allDays
      );
      let planDaysNames = planDaysMembers
        .map((item) => item.nickname)
        .join("、");

      strs.push(`汇总：共<a>${allDays}</a>天`);
      strs.push(`共<a>${this.members.length}</a>人`);
      strs.push(`达成<a>全面日毕</a>的有<a>${daytodayMembers.length}</a>人`);
      if (planDaysMembers.length > 0) {
        strs.push(`达成<a>说到做到</a>的有：<a>${planDaysNames}</a>`);
      }

      str += "<span>" + strs.join("，") + "</span>";
      return str;
    },
  },
  watch: {
    selectMember() {
      this.initEcharts();
    },
  },
  mounted() {
    this.initData();
  },
  methods: {
    initData() {},
    // 分析
    async doAnaly() {
      this.isLoading = true;
      // await this.readCSV();
      await this.readQQRecords();
      this.isLoading = false;
      this.initEcharts();
      new this.$tableSelect(".analy-box-wrap .table");
    },
    getTimeClass(plan, time) {
      if (!time) {
        return "";
      }
      let nowDate = dayjs().format("YYYY-MM-DD");
      let curTime;
      if (time.indexOf("-") > 0) {
        curTime = dayjs(time);
      } else {
        curTime = dayjs(nowDate + " " + time);
      }
      let className = "";
      if (time.indexOf("补") > -1) {
        className = "level4";
      } else if (curTime.isAfter(nowDate + " 23:50:00")) {
        className = "level3";
      } else if (curTime.isAfter(nowDate + " 23:30:00")) {
        className = "level2";
      } else if (plan && curTime.isAfter(nowDate + " " + plan)) {
        className = "level1";
      }
      return className;
    },
    // echarts
    initEcharts() {
      let xData = this.periodCountXdata.map((item) => item.min);
      let values = this.periodCountData;
      let option = {
        grid: {
          left: 30,
          right: 10,
          top: 10,
          bottom: 30,
        },
        xAxis: {
          type: "category",
          data: xData,
          axisLabel: {
            interval: 1,
          },
        },
        yAxis: {
          type: "value",
        },
        series: [
          {
            data: values,
            type: "bar",
            showBackground: true,
            backgroundStyle: {
              color: "rgba(180,180,180,0.2)",
            },
            itemStyle: {
              borderRadius: [4, 4, 0, 0],
            },
          },
        ],
      };
      if (!this.timeChart) {
        let dom = this.$refs.timeCountChart;
        this.timeChart = echarts.init(dom);
      }
      this.timeChart.setOption(option, true);
    },
    // 时间表格
    getTimeList(qq) {
      let list = [];
      for (let i = 0, n = this.timeList.length; i < n; i++) {
        let item = this.timeList[i];
        if (item.qq === qq) {
          list = item.weeks;
          break;
        }
      }
      return list;
    },
    // 统计
    getCountsByQQ(qq) {
      let timeList = this.getTimeList(qq);
      let allDays = 0; // 所有天数
      let delayDays = 0; // 超时交作业
      let delayTimes = [];
      let deadlineDays = 0; // 踩点
      let focusDays = 0; // 23:30之后交的
      let missPlanDays = 0; // 错过自己规定时间的
      let planDays = 0; // 说到做到的
      let nowDate = dayjs().format("YYYY-MM-DD");

      for (let i = 0, n = timeList.length; i < n; i++) {
        let days = timeList[i].days || [];
        let plan = timeList[i].plan || "";
        let normalDates = timeList[i].normalDates || [];
        for (let j = 0, m = days.length; j < m; j++) {
          let time = days[j];
          if (!time || time === "-") {
            continue;
          }
          let normalDate = normalDates[j];
          allDays += 1;
          let curTime;
          if (time.indexOf("-") > 0) {
            curTime = dayjs(time);
          } else {
            curTime = dayjs(nowDate + " " + time);
          }
          if (time.indexOf("补") > -1) {
            delayDays += 1;
            delayTimes.push(this.getDelayTime(time, normalDate));
          } else if (curTime.isAfter(nowDate + " 23:50:00")) {
            deadlineDays += 1;
          } else if (curTime.isAfter(nowDate + " 23:30:00")) {
            focusDays += 1;
          } else if (
            plan &&
            curTime.add(-10, "minute").isAfter(nowDate + " " + plan)
          ) {
            missPlanDays += 1;
          } else {
            planDays += 1;
          }
        }
      }
      return {
        allDays,
        daytoDays: allDays - delayDays,
        delayDays,
        deadlineDays,
        focusDays,
        missPlanDays,
        planDays,
        delayTimes,
      };
    },
    // 获取超时时间
    getDelayTime(time, _normalDate) {
      let curTime = dayjs(time.replace("（补）", ""));
      let normalDate = _normalDate;
      normalDate = "2022-" + normalDate.replace("月", "-").replace("日", "");
      let delayTime = dayjs(normalDate).add(1, "day");

      return delayTime.to(curTime);
    },
    // 更改排序
    changeSort(key, order) {
      this.sortKey = key;
      this.sortOrder = order;
    },
    // 获取排序order
    getSortOrder(key) {
      if (key === this.sortKey) {
        return this.sortOrder;
      }
      return "";
    },
  },
};
</script>

<style lang="less">
.time-analy-result {
  padding: 20px 0;
}
.result-summary {
  span {
    font-weight: 600;
  }
  a {
    padding: 0 2px;
    color: red;
  }
  // max-width: 600px;
  max-height: 18px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: inline-block;
}
.result-summary-expand {
  max-height: 300px;
}
.time-analy-table {
  th,
  td {
    width: 80px;
    height: 26px;
    display: inline-block;
    white-space: nowrap;
    overflow: hidden;
    text-align: center;
    color: #000;
    border-color: rgba(200, 200, 200, 0.6) !important;
  }
  .level4 {
    background-color: red;
  }
  .level3 {
    background-color: #e36162;
  }
  .level2 {
    background-color: #f3925d;
  }
  .level1 {
    background-color: #fccda9;
  }
}
.time-count-echart {
  width: 500px;
  height: 300px;
  display: inline-block;
  vertical-align: middle;
}
.time-count-tops {
  display: inline-block;
  vertical-align: middle;
  margin-left: 10px;
  margin-top: -10px;
  table {
    min-width: initial;
    td,
    th {
      max-width: 140px;
      line-height: 22px;
      padding: 0px 4px;
      white-space: nowrap;
      border: 1px solid rgba(200, 200, 200, 0.6);
      text-align: center;
    }
  }
}
</style>
